/*
   This class can be inheritted from to create forms as widgets.
   
   Please remember to add any widgets you want validated to this.mChildWidgets.
   The class expects a JSON responce for an error AND an error code to be set in the HTTP responce header.  Besed used with NoBuisnessBase/Utility/Status on the Zend side.
*/
define(
   [
      'dojo/_base/declare',
      'dojo/_base/lang',
      'dojo/_base/array',
      'dojo/_base/json',
      'dojo/Evented',
      'dijit/_WidgetBase',
      'dijit/_TemplatedMixin',
      'dijit/Tooltip'
   ],
   function(declare, lang, array, json, evented, _WidgetBase, _TemplatedMixin, Tooltip)
   {
      return declare([_WidgetBase, _TemplatedMixin, evented],
      {
         widgetsInTemplate: true,
      
         postCreate: function()
         {
            this.inherited(arguments);
            this.mChildWidgets = [];
            this.mToolTips = [];
         },
         setForm: function(pForm)
         {
            this.mForm = pForm;
         },
         getChildren: function()
         {
            var children = this.inherited(arguments);
            if(this.mChildWidgets)
               children = children.concat(this.mChildWidgets);

            return children;
         },
         submitForm: function()
         {
            if(!this.mForm)
               return;
            
            dojo.forEach(this.mToolTips, function(pToolTip, i)
            {
               pToolTip.destroyRecursive();
            }, this);
            this.mToolTips = [];
            
            var xhrArgs = {
               form: this.mForm.domNode,
               url: this.action,
               handleAs: "json",
               failOk: true,
               load: lang.hitch(this, function(data){
                  this.postSubmit(data, false);
               }),
               error: lang.hitch(this, function(error){
                  var data = dojo.fromJson((error.responseText));
                  
                  array.forEach(this.mForm._getDescendantFormWidgets(), lang.hitch(this, function(pWidget){
                     if(!data)
                        return;
                     
                     // Display errors on widgets
                     for(var i in data.extraInfo)
                     {
                        if(!data.extraInfo.hasOwnProperty(i))
                           continue;

                        if(pWidget.name != i)
                           continue;
         
                        // Set pWidget to error state
                        pWidget.state = "Error";
                        pWidget._setStateClass();
                        dijit.setWaiState(pWidget.focusNode, "invalid", "true");
         
                        // get message
                        var msg = "";
                        if(data.extraInfo[i].length !== null)
                        {
                           for(var m in data.extraInfo[i])
                           {
                              if(!data.extraInfo[i].hasOwnProperty(m))
                                 continue;

                              msg = data.extraInfo[i][m];
                           }
                        }
                        else
                           msg = data.extraInfo[i];
         
                        // Set tooltip if message exists
                        if(msg !== "")
                        {
                           var toolTip = new Tooltip({
                              connectId: pWidget.domNode,
                              label: msg,
                              showDelay: 0
                           });
                           this.mToolTips.push(toolTip);
                        }
                     }

                     console.log(pWidget);
                  }));
                  this.postSubmit(data, true);
               })
            };
            
            this.preSubmit();
            
            // Call the asynchronous xhrPost
            var deferred = dojo.xhrPost(xhrArgs);
         },
         preSubmit: function()
         {
         },
         postSubmit: function(data, error)
         {
            if(!error)
               this.emit("formExecuted", data);
         }
      });
   }
);
